package com.fatmeraid.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fatmeraid.common.exception.FarmException;
import com.fatmeraid.common.login.LoginUser;
import com.fatmeraid.common.login.LoginUserHolder;
import com.fatmeraid.common.model.PageResult;
import com.fatmeraid.common.result.ResultCodeEnum;
import com.fatmeraid.dao.ProductDao;
import com.fatmeraid.dao.ProductTypeDao;
import com.fatmeraid.dao.UserDao;
import com.fatmeraid.domain.Product;
import com.fatmeraid.domain.ProductType;
import com.fatmeraid.service.ProductService;
import com.fatmeraid.vo.PaginationVo;
import com.fatmeraid.vo.product.ReviewProductVo;
import com.fatmeraid.vo.product.UploadVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProductServiceImpl implements ProductService {
	@Autowired
	private ProductDao productDao;
	@Autowired
	private ProductTypeDao productTypeDao;
	@Autowired
	private UserDao userDao;
	@Override
	public Long uploadProduct(UploadVo uploadVo) {
		// 获取当前农户id
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();
		Integer roleType = userDao.selectById(userId).getRoleType();
		if (!roleType.equals(2) && !roleType.equals(3)){
			throw new FarmException(ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN);
		}

		// 判断商品类型是否存在
		ProductType productType = productTypeDao.selectById(uploadVo.getProductTypeId());
		if (productType == null){
			throw new FarmException(ResultCodeEnum.FAIL);
		}

		Product product =new Product();
		product.setFarmerId(userId);
		product.setProductTypeId(uploadVo.getProductTypeId());
		product.setProductName(uploadVo.getProductName());
		product.setDescription(uploadVo.getDescription());
		product.setPrice(uploadVo.getPrice());
		product.setStock(uploadVo.getStock());
		product.setOrigin(uploadVo.getOrigin());
		int insert = productDao.insert(product);
		if (insert <= 0){
			throw new FarmException(ResultCodeEnum.FAIL);
		}
		return product.getProductId();
	}

	@Override
	public PageResult<Product> getProductList(PaginationVo paginationVo) {
		// 判断当前权限
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();
		Integer roleType = userDao.selectById(userId).getRoleType();
		// 创建分页对象
		IPage<Product> page = new Page<>(paginationVo.getCurrent(), paginationVo.getSize());

		// 创建查询条件
		QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
		String keyword = paginationVo.getKeyword();
		if (paginationVo.getKeyword() != null && !paginationVo.getKeyword().isEmpty()) {
			queryWrapper.like("product_name", keyword);
		}
		if (roleType == 1){
			// 获取上架的商品
			queryWrapper.eq("status", 2);
		}
		if (roleType == 2){
			queryWrapper.eq("farmer_id", userId);
		}
		queryWrapper.orderByDesc("create_time");

		// 执行分页查询
		IPage<Product> userIPage = productDao.selectPage(page, queryWrapper);

		return new PageResult<>(userIPage.getTotal(), userIPage.getRecords());
	}

	@Override
	public Product getProductById(Long id) {
		// 获取商品信息
		Product product = productDao.selectById(id);
		// 获取商品类型id
		Integer typeId = product.getProductTypeId();
		// 获取商品类型名称
		ProductType productType = productTypeDao.selectById(typeId);
		// 设置商品类型名称
		product.setProductTypeName(productType.getTypeName());
		// 返回商品信息
		return product;
	}

	@Override
	public boolean auditProduct(ReviewProductVo reviewProductVo) {
		// 查看当前权限
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();
		Integer roleType = userDao.selectById(userId).getRoleType();
		if (roleType != 2 && roleType != 3){
			throw new FarmException(ResultCodeEnum.ADMIN_ACCESS_FORBIDDEN);
		}

		if (reviewProductVo.getProductId() == null|| reviewProductVo.getStatus()<0|| reviewProductVo.getStatus()>3){
			throw new FarmException(ResultCodeEnum.PARAM_ERROR);
		}

		Product product = new Product();
		product.setProductId(reviewProductVo.getProductId());
		product.setStatus(reviewProductVo.getStatus());

		// 获取当前状态
		Integer status = productDao.selectById(reviewProductVo.getProductId()).getStatus();

		// 记录sql执行的结果
		int ret = 0;

		// 农户权限
		if (roleType == 2){

			// 可以将上架的商品改为下架
			if (status==2 && reviewProductVo.getStatus()==3){
				ret = productDao.updateById(product);
			}else {
				throw new FarmException(ResultCodeEnum.FAIL);
			}
		}
		// 管理员权限
		if (roleType == 3){
			// 可以将待审核的商品改为上架或未通过
			ret = productDao.updateById(product);
		}

		return ret>0;
	}

	@Override
	public boolean deleteProduct(Long id) {
		int i = productDao.deleteById(id);
		return i>0;
	}


	// 获取所有已经上架的商品
	@Override
	public PageResult<Product> getAllOnSale(PaginationVo paginationVo) {
		// 创建分页对象
		IPage<Product> page = new Page<>(paginationVo.getCurrent(), paginationVo.getSize());
		// 创建查询条件
		QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
		String keyword = paginationVo.getKeyword();
		if (paginationVo.getKeyword() != null && !paginationVo.getKeyword().isEmpty()) {
			queryWrapper.like("product_name", keyword);
		}
		queryWrapper.eq("status", 2);
		// 执行分页查询
		IPage<Product> userIPage = productDao.selectPage(page, queryWrapper);

		return new PageResult<>(userIPage.getTotal(), userIPage.getRecords());
	}


}
